<template>
  <Form class="xtx-form"  :validation-schema="mySchema" v-slot="{errors}" ref="formCom" autocomplete="off">
    <div class="xtx-form-item">
      <div class="field">
        <i class="icon iconfont icon-user"></i>
        <Field :class="{err: errors.account}" v-model="form.account" class="input" type="text" placeholder="请输入用户名" name="account" />
      </div>
      <div class="error" v-if="errors.account">{{ errors.account }}</div>
    </div>
    <div class="xtx-form-item">
      <div class="field">
        <i class="icon iconfont icon-phone"></i>
        <Field :class="{err: errors.mobile}"  v-model="form.mobile" class="input" type="text" placeholder="请输入手机号" name="mobile" />
      </div>
      <div class="error" v-if="errors.mobile">{{ errors.mobile }}</div>
    </div>
    <div class="xtx-form-item">
      <div class="field">
        <i class="icon iconfont icon-code"></i>
        <Field :class="{err: errors.code}" v-model="form.code" class="input" type="text" placeholder="请输入验证码" name="code"/>
        <span class="code" @click="send()">{{ time>0? `${time}秒后重新发送`: '发送验证码' }}</span>
      </div>
      <div class="error" v-if="errors.code">{{ errors.code }}</div>
    </div>
    <div class="xtx-form-item">
      <div class="field">
        <i class="icon iconfont icon-lock"></i>
        <Field :class="{err: errors.password}" v-model="form.password" class="input" type="password" placeholder="请输入密码" name="password" />
      </div>
      <div class="error" v-if="errors.password">{{ errors.password }}</div>
    </div>
    <div class="xtx-form-item">
      <div class="field">
        <i class="icon iconfont icon-lock"></i>
        <Field :class="{err: errors.rePassword}" v-model="form.rePassword" class="input" type="password" placeholder="请确认密码" name="rePassword" />
      </div>
      <div class="error" v-if="errors.rePassword">{{ errors.rePassword }}</div>
    </div>
    <a href="javascript:;" class="submit" @click="submit()">立即提交</a>
  </Form>
</template>

<script>
import { Form, Field } from 'vee-validate'
import { ref, reactive, onMounted } from 'vue'
import { userQQPatchCode, userQQPatchLogin } from '@/api/user'
import schema from '@/utils/vee-validate-schema'
import { useIntervalFn } from '@vueuse/core'
import Message from '@/components/library/Message'
import { useStore } from 'vuex'
import { useRouter } from 'vue-router'
export default {
  name: 'CallbackPatch',
  components: {
    Form,
    Field
  },
  props: {
    unionId: {
      type: String,
      default: ''
    }
  },
  setup (props, { emit }) {
    const formCom = ref(null)

    // 表单数据对象
    const form = reactive({
      account: null,
      mobile: null,
      code: null,
      password: null,
      rePassword: null
    })

    // 表单规则
    const mySchema = {
      account: schema.accountApi,
      mobile: schema.mobile,
      code: schema.code,
      password: schema.password,
      rePassword: schema.rePassword
    }

    const time = ref(0)
    const { pause, resume } = useIntervalFn(() => {
      time.value--
      if (time.value === 0) {
        resume()
      }
    }, 1000, false)

    // 当定时器走完的时候,将定时器销毁
    onMounted(() => {
      pause()
    })

    // 点击发送验证码的时候
    const send = async () => {
      const valid = mySchema.mobile(form.mobile)
      if (valid === true) {
        try {
          await userQQPatchCode(form.mobile)
          Message({ text: '发送成功成功', type: 'success' })
          time.value = 60
          resume()
        } catch (err) {
          Message({ text: err.response.data.message, type: 'error' })
        }
      } else {
        formCom.value.setFieldError('mobile', valid)
      }
    }

    const store = useStore()
    const router = useRouter()
    const submit = () => {
      const valid = formCom.value.validate()
      if (valid) {
        userQQPatchLogin({
          unionId: props.unionId,
          ...form
        }).then(data => {
          const { id, mobile, token, nickname, avatar } = data.result
          store.commit('user/setUser', { id, mobile, token, nickname, avatar })
          store.dispatch('cart/mergeLocalCart').then(() => {
            router.push(store.state.user.redirectUrl || '/')
            Message({ text: '绑定成功', type: 'success' })
          })
        }).catch(err => {
          console.log(err)
          Message({ text: '绑定失败', type: 'error' })
        })
      }
    }
    return { form, mySchema, schema, formCom, send, time, submit }
  }
}
</script>

<style scoped lang='less'>
.code {
  position: absolute;
  right: 0;
  top: 0;
  line-height: 50px;
  min-width: 80px;
  padding: 0 6px;
  color: #999;
  &:hover {
    cursor: pointer;
  }
}
</style>
